package com.curry.android.http;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.HttpStatus;

import android.os.Handler;
import android.util.Log;

import com.curry.android.callback.ICallBack;
import com.curry.android.core.HttpConnStatus;
import com.curry.android.core.JsonHttpServlet;
import com.curry.android.core.IHttpServlet;
import com.curry.android.util.JSONHelper;

@Deprecated
public class HttpUtil {

    private String Tag = null;
    private IHttpServlet http;
    public static final int ACTION_URI = 0;
    public static final int ACTION_JSON = 1;
    public static final int ACTION_XML = 2;
    public static final String ERROR = "{\"errCode\": 6011,\"errInfo\": \"网络连接失败\"}";
    public static HttpUtil hu = null;
    /** HTTP请求线程池 */
    private ExecutorService executorService;
    private HashMap<String, String> header = new HashMap<>();
    private boolean isDebug;
    private boolean isHeaderDebug;

    public static HttpUtil getHttp() {
        if (hu == null) {
            hu = new HttpUtil();
        }
        return hu;
    }

    public void setDebug(boolean isDebug) {
        this.isDebug = isDebug;
    }

    public void setHeaderDebug(boolean isHeaderDebug) {
        this.isHeaderDebug = isHeaderDebug;
    }

    private void initHeader() {
        if (header == null) {
            header = new HashMap<>();
        }
        header.put("charset", "utf-8");
        header.put("Content-Type", "application/json");
        header.put("app", "android");
    }

    public void setHeader(HashMap<String, String> header) {
        this.header = header;
    }

    public void setHeader(String key, String value) {
        if (header == null) {
            initHeader();
        }
        if (key != null && value != null) {
            header.put(key, value);
        }
    }

    private String serverURL = "";

    public void setServerURL(String serverURL) {
        this.serverURL = serverURL;
    }

    private HttpUtil() {
        executorService = Executors.newFixedThreadPool(3);
        initHeader();
    }

    /**
     * @param url      http提交的地址
     * @param map      数据存储方式
     * @param wat      handler返回的识别码
     * @param handler
     * @param callBack 回调类
     * @throws Exception
     */
    public void get(String url, Map<String, Object> map, int wat, Handler handler, ICallBack callBack) throws Exception {
        get(url, map, wat, handler, callBack, 0);
    }

    /**
     * @param url      http提交的地址
     * @param map      数据存储方式
     * @param wat      handler返回的识别码
     * @param handler
     * @param callBack 回调类
     * @param action   提交方式0: url 1:object
     * @throws Exception
     */
    public void get(String url, Map<String, Object> map, int wat, Handler handler, ICallBack callBack, int action) throws Exception {
        String uri = assemblyRestUrl(url, map);
        String params = null;
        switch (action) {
            case ACTION_URI:
                String parame = assemblyUrl(map);
                if (uri.indexOf("?") == -1) {
                    if (uri.lastIndexOf("/") != uri.length() - 1) {
                        if (parame != null && !"".equals(parame))
                            uri = uri + "?";
                    }
                }

                uri = uri + parame;
                break;
            case ACTION_JSON:
                params = JSONHelper.Map2Json(map);
                break;
            default:
                break;
        }
        http2Get(uri, wat, params, callBack, handler);
    }

    /**
     * @param url      http提交的地址
     * @param map      数据存储方式
     * @param wat      handler返回的识别码
     * @param handler
     * @param callBack 回调类
     * @param action   提交方式0: url 1:object
     * @throws Exception
     */

    public void post(String url, Map<String, Object> map, int wat, Handler handler, ICallBack callBack, int action) throws Exception {
        String uri = assemblyRestUrl(url, map);
        String params = null;
        switch (action) {
            case 0:
                String parame = assemblyUrl(map);
                if (uri.indexOf("?") == -1) {
                    if (uri.lastIndexOf("/") != uri.length() - 1) {
                        if (parame != null && !"".equals(parame))
                            uri = uri + "?";
                    }
                }
                uri = uri + assemblyUrl(map);
                break;
            case 1:
                params = JSONHelper.Map2Json(map);
                if (isDebug) {
                    Log.e(HttpUtil.class.getSimpleName(), "url = " + url + " , post param = " + params);
                }
                break;
            default:
                break;
        }
        http2Post(uri, wat, params, callBack, handler);
    }

    /**
     * @param url      http提交的地址
     * @param map      数据存储方式
     * @param wat      handler返回的识别码
     * @param handler
     * @param callBack 回调类
     * @param action   提交方式0: url 1:object
     * @throws Exception
     */

    public void put(String url, Map<String, Object> map, int wat, Handler handler, ICallBack callBack, int action) throws Exception {
        String uri = assemblyRestUrl(url, map);
        String params = null;
        switch (action) {
            case 0:
                String parame = assemblyUrl(map);
                if (uri.indexOf("?") == -1) {
                    if (uri.lastIndexOf("/") != uri.length() - 1) {
                        if (parame != null && !"".equals(parame))
                            uri = uri + "?";
                    }
                }
                uri = uri + assemblyUrl(map);
                break;
            case 1:
                params = JSONHelper.Map2Json(map);
                if (isDebug) {
                    Log.e(HttpUtil.class.getSimpleName(), "url = " + url + " , post param = " + params);
                }
                break;
            default:
                break;
        }
        http2put(uri, wat, params, callBack, handler);
    }

    /**
     * @param url
     * @param map
     * @param wat
     * @param handler
     * @param callBack
     * @throws Exception
     */
    public void delete(String url, Map<String, Object> map, int wat, Handler handler, ICallBack callBack) throws Exception {
        String uri = assemblyRestUrl(url, map);

        String parame = assemblyUrl(map);
        if (uri.indexOf("?") == -1) {
            if (uri.lastIndexOf("/") != uri.length() - 1) {
                if (parame != null && !"".equals(parame))
                    uri = uri + "?";
            }
        }
        uri = uri + assemblyUrl(map);

        http2delete(uri, wat, callBack, handler);
    }

    /**
     * @param uri
     * @param wat
     * @param callBack
     * @param handler
     * @throws Exception
     */
    private void http2delete(final String uri, final int wat, final ICallBack callBack, final Handler handler) throws Exception {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    http = new JsonHttpServlet(URLHelper.getURL(serverURL, uri), header, isDebug, isHeaderDebug);
                    HttpConnStatus hcs = http.delete();
                    if (hcs.getCode() != HttpStatus.SC_OK) {
                        callBack.request(ERROR, handler, HttpStatus.SC_INTERNAL_SERVER_ERROR);
                    } else {
                        callBack.request(hcs.getDescribe(), handler, wat);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * @param uri
     * @param wat
     * @param params
     * @param callBack
     * @param handler
     * @throws Exception
     */
    private void http2put(final String uri, final int wat, final String params, final ICallBack callBack, final Handler handler) throws Exception {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    http = new JsonHttpServlet(URLHelper.getURL(serverURL, uri), header, params, isDebug, isHeaderDebug);
                    HttpConnStatus hcs = http.put();
                    if (hcs.getCode() != HttpStatus.SC_OK) {
                        callBack.request(ERROR, handler, HttpStatus.SC_INTERNAL_SERVER_ERROR);
                    } else {
                        callBack.request(hcs.getDescribe(), handler, wat);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }


    private void http2Get(final String uri, final int wat, final String params, final ICallBack callBack, final Handler handler) throws Exception {

        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    http = new JsonHttpServlet(URLHelper.getURL(serverURL, uri), header, params, isDebug, isHeaderDebug);
                    HttpConnStatus hcs = http.get();
                    if (hcs.getCode() != HttpStatus.SC_OK) {
                        callBack.request(ERROR, handler, HttpStatus.SC_INTERNAL_SERVER_ERROR);
                    } else {
                        callBack.request(hcs.getDescribe(), handler, wat);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }


    /**
     * 0 成功 1失败 500 连接不上服务器
     *
     * @param handler
     * @throws Exception
     */
    private void http2Post(final String uri, final int wat, final String params, final ICallBack callBack, final Handler handler) throws Exception {
        executorService.submit(new Runnable() {
            @Override
            public void run() {

                try {
                    http = new JsonHttpServlet(URLHelper.getURL(serverURL, uri), header, params, isDebug, isHeaderDebug);
                    HttpConnStatus hcs = http.post();
                    if (hcs.getCode() != HttpStatus.SC_OK) {
                        callBack.request(ERROR, handler, HttpStatus.SC_INTERNAL_SERVER_ERROR);
                    } else {
                        callBack.request(hcs.getDescribe(), handler, wat);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }


    private String assemblyRestUrl(String url, Map<String, Object> map) {
        String uri = url;
        if (map != null) {

            Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();

            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                if (entry.getKey().indexOf("{") > -1 || entry.getKey().indexOf("}") > -1) {
                    uri = uri.replace(entry.getKey(), entry.getValue().toString());
                }
            }

            return uri;
        } else {
            return uri;
        }

    }

    private String assemblyUrl(Map<String, Object> map) {
        if (map != null) {
            StringBuffer sb_url = new StringBuffer();
            Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();

            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                if (entry.getKey().indexOf("{") > -1 || entry.getKey().indexOf("}") > -1) {
                    continue;
                }
                if (entry.getKey().equals("accesToken") || entry.getKey().equals("authToken") || entry.getKey().equals("Tag") || entry.getKey().equals("Dialog")) {
                    continue;
                }
                sb_url.append("&");
                sb_url.append(entry.getKey());
                sb_url.append("=");
                sb_url.append(entry.getValue());
            }
            if ("".equals(sb_url.toString())) return "";
            return sb_url.toString().substring(1);
        } else {
            return "";
        }


    }


    private void Log(String tag, String msg) {
        android.util.Log.i(tag, msg);
    }

}
